package com.thoughtworks.rhinoextension;

import org.mozilla.javascript.*;
import org.mozilla.javascript.tools.*;
import org.mozilla.javascript.tools.shell.*;

public class RhinoShell {

    private ShellContextFactory shellContextFactory = new ShellContextFactory();
    private Global global = new Global();
    private boolean globalInitialized = false;

    public static void main(String args[]) {
        String jsFile = "/home/isaachan/opensrc/JSpecPlugin/rhinoextension/js/runner.js";
        RhinoShell shell = new RhinoShell();
        ScriptableObject testResults = (ScriptableObject) shell.exec(jsFile);

        System.out.println(testResults);

        ScriptableObject stats = (ScriptableObject) testResults.get("stats", testResults);
        System.out.println(stats.get("passes", stats));
        System.out.println(stats.get("failures", stats));

        ScriptableObject allSutes = (ScriptableObject) testResults.get("allSuites", testResults);
        System.out.println(allSutes.get("length", allSutes));
    }

    public Object exec(String origArgs) {
        ToolErrorReporter errorReporter = new ToolErrorReporter(false, System.out);
        shellContextFactory.setErrorReporter(errorReporter);

        if (!globalInitialized) {
            global.init(shellContextFactory);
            globalInitialized = true;
        }

        return shellContextFactory.call(new RunJSpecTestsAction(origArgs, global, shellContextFactory));
    }


}
